<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span style="font-size: 25px; font-weight: bold; ">文章管理</span>
                <div class="extra">
                    <el-button type="primary" @click="visibleDrawer = true">添加文章</el-button>
                </div>
            </div>
        </template>

        <!-- 搜索表单 -->
        <el-form inline>
            <!-- 父栏目选择 -->
            <el-form-item label="父栏目：" v-if="parentColumns.length > 0">
                <el-select placeholder="请选择" v-model="parentColumnId" @change="onParentColumnChange" clearable>
                    <el-option v-for="pc in parentColumns" :key="pc.columnId" :label="pc.name" :value="pc.columnId">
                        <template #default>
                            <span>{{ pc.name }}</span>
                            <el-tag size="small" style="margin-left: 10px;">{{ pc.type }}</el-tag>
                        </template>
                    </el-option>
                </el-select>
            </el-form-item>

            <!-- 子栏目选择 -->
            <el-form-item label="子栏目：" v-if="subColumns.length > 0">
                <el-select placeholder="请选择" v-model="subColumnId" clearable>
                    <el-option v-for="sc in subColumns" :key="sc.columnId" :label="sc.name" :value="sc.columnId">
                        <template #default>
                            <span>{{ sc.name }}</span>

                        </template>
                    </el-option>
                </el-select>
            </el-form-item>


            <el-form-item label="发布状态：">
                <el-select placeholder="请选择" v-model="state">
                    <el-option label="已发布" value="已发布"></el-option>
                    <el-option label="草稿" value="草稿"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="searchArticles">搜索</el-button>
                <el-button @click="resetFilters">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 文章列表 -->
        <el-table :data="articles" style="width: 100%" height="calc(100vh - 200px)" :max-height="600" border>
            <!-- 使用 scoped slot 来处理每一行的数据 -->
            <el-table-column label="父栏目" prop="parentColumnName" min-width="100"></el-table-column>
            <el-table-column label="子栏目" prop="subColumnName" min-width="100"></el-table-column>
            <el-table-column label="标题" width="400" prop="title">
                <template #default="{ row }">
                    <div class="cell-ellipsis">{{ row.title }}</div>
                </template>
            </el-table-column>
            <el-table-column label="简介" prop="resume">
                <template #default="{ row }">
                    <div class="cell-ellipsis">{{ row.resume }}</div>
                </template>
            </el-table-column>
            <el-table-column label="封面图" width="150">
                <template #default="{ row }">
                    <img v-if="row.coverImageUrl" :src="row.coverImageUrl" @click="openImage(row.coverImageUrl)" alt="封面图"
                        style="cursor: pointer; width: 100px; height: auto;">
                    <span v-else>无封面图</span>
                </template>
            </el-table-column>
            <el-table-column label="状态" prop="state" width="100">
                <template #default="{ row }">
                    <el-tag :type="row.state === '已发布' ? 'success' : 'info'">{{ row.state }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createdTime" min-width="180"></el-table-column>
            <el-table-column label="操作" width="120">
                <template #default="{ row }">
                    <el-button :icon="Edit" circle  type="primary" @click="handleEdit(row.articleId)"
                        title="编辑"></el-button>
                    <el-button :icon="Delete" circle type="danger" @click="deleteArticle(row)" title="删除"></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />



        <!-- 图片查看器 -->
        <el-dialog v-model="dialogVisible" title="封面图预览" width="20%" top="30vh">
            <img :src="largeImageUrl" alt="封面图" style="max-width: 100%; max-height: 80vh;">
        </el-dialog>



      
        <!-- 添加文章抽屉 -->
        <el-drawer v-model="visibleDrawer" title="添加文章" direction="rtl" size="50%">
            <!-- 添加文章表单 -->
            <el-form :model="articleModel" label-width="100px" :rules="rules">
                <!-- 父栏目选择 -->
                <el-form-item label="栏目">
                    <el-select placeholder="请选择父栏目" v-model="articleModel.parentColumnId" @change="onParentColumnChange2">
                        <el-option v-for="pc in parentColumns" :key="pc.columnId" :label="pc.name" :value="pc.columnId">
                            <template #default>
                                <span>{{ pc.name }}</span>
                                <el-tag size="small" style="margin-left: 10px;">{{ pc.type }}</el-tag>
                            </template>
                        </el-option>
                    </el-select>

                    <!-- 子栏目选择 -->
                    <el-select placeholder="请选择子栏目" v-model="articleModel.subColumnId">
                        <el-option v-for="sc in subColumns" :key="sc.columnId" :label="sc.name" :value="sc.columnId">
                            <template #default>
                                <span>{{ sc.name }}</span>
                            </template>
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="文章标题" prop="title">
                    <el-input v-model="articleModel.title" placeholder="请输入标题"></el-input>
                </el-form-item>

                <el-form-item label="文章来源">
                    <el-input v-model="articleModel.source" placeholder="请输入文章来源"></el-input>
                </el-form-item>

                <el-form-item label="文章简介">
                    <el-input v-model="articleModel.resume" placeholder="请输入文章简介"></el-input>
                </el-form-item>

                <el-form-item label="文章封面">
                    <!-- 
                        auto-upload:设置是否自动上传
                        action:设置服务器接口路径
                        name:设置上传的文件字段名
                        headers:设置上传的请求头
                        on-success:设置上传成功的回调函数
                     -->
                    <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false" action="/api/upload"
                        name="file" :headers="{ 'Authorization': tokenStore.token }" :on-success="uploadSuccess">
                        <img v-if="articleModel.coverImageUrl" :src="articleModel.coverImageUrl" class="avatar" />

                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>

                <el-form-item label="视频上传">
                    <el-upload class="upload-demo" action="/api/upload" :headers="{ 'Authorization': tokenStore.token }"
                        :on-success="handleVideoSuccess" :before-upload="beforeVideoUpload" :file-list="videoFileList">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <template #tip>
                            <div class="el-upload__tip">只能上传视频文件，且不超过500MB</div>
                        </template>
                    </el-upload>
                </el-form-item>


                <el-form-item label="详情内容">
                    <div class="editor">
                        <quill-editor 
                            theme="snow" 
                            v-model:content="articleModel.content" 
                            contentType="html"
                            :options="editorOptions"
                        ></quill-editor>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addArticle('已发布')">发布</el-button>
                    <el-button type="info" @click="addArticle('草稿')">草稿</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>

        <!-- 编辑文章抽屉 -->
        <el-drawer v-model="visibleEditDrawer" title="编辑文章" direction="rtl" size="50%">
            <!-- 编辑文章表单 -->
            <el-form :model="articleDetail" label-width="100px">
                <!-- 父栏目选择 -->
                <el-form-item label="栏目">
                    <el-select placeholder="请选择父栏目" v-model="articleDetail.parentColumnId" @change="onParentColumnChange2">
                        <el-option v-for="pc in parentColumns" :key="pc.columnId" :label="pc.name" :value="pc.columnId">
                            <template #default>
                                <span>{{ pc.name }}</span>
                                <el-tag size="small" style="margin-left: 10px;">{{ pc.type }}</el-tag>
                            </template>
                        </el-option>
                    </el-select>

                    <!-- 子栏目选择 -->
                    <el-select placeholder="请选择子栏目" v-model="articleDetail.subColumnId">
                        <el-option v-for="sc in subColumns" :key="sc.columnId" :label="sc.name" :value="sc.columnId">
                            <template #default>
                                <span>{{ sc.name }}</span>
                            </template>
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="文章标题">
                    <el-input v-model="articleDetail.title" placeholder="请输入标题"></el-input>
                </el-form-item>

                <el-form-item label="文章来源">
                    <el-input v-model="articleDetail.source" placeholder="请输入文章来源"></el-input>
                </el-form-item>

                <el-form-item label="文章简介">
                    <el-input v-model="articleDetail.resume" placeholder="请输入文章简介"></el-input>
                </el-form-item>

                <el-form-item label="文章封面">
                    <!-- 封面图片上传 -->
                    <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false" action="/api/upload"
                        name="file" :headers="{ 'Authorization': tokenStore.token }" :on-success="uploadSuccess2">
                        <img v-if="articleDetail.coverImageUrl" :src="articleDetail.coverImageUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>

                <el-form-item label="视频上传">
                    <!-- 视频上传 -->
                    <el-upload class="upload-demo" action="/api/upload" :headers="{ 'Authorization': tokenStore.token }"
                        :on-success="handleVideoSuccess2" :before-upload="beforeVideoUpload" :file-list="videoFileList">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <template #tip>
                            <div class="el-upload__tip">只能上传视频文件，且不超过500MB</div>
                        </template>
                    </el-upload>
                </el-form-item>

                <el-form-item label="详情内容">
                    <div class="editor">
                        <quill-editor 
                            theme="snow" 
                            v-model:content="articleDetail.content"
                            contentType="html"
                            :options="editorOptions"
                        ></quill-editor>
                    </div>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="updateArticle">保存</el-button>
                    <el-button type="primary" v-if="articleDetail.state === '草稿'"
                    @click="() => updateArticle('已发布')">发布</el-button>
                    <el-button @click="visibleEditDrawer = false">取消</el-button>
                </el-form-item>


            </el-form>
        </el-drawer>

    </el-card>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Edit, Delete } from '@element-plus/icons-vue'
import { pColumnListService, columnsService, AllChildrencolumnsService, articleListService, articleAddService, articleDetailService, articleUpdateService, deleteArticleService } from '@/api/articles.js'
import { onMounted } from 'vue';
import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { ElMessage } from 'element-plus'
import { ElMessageBox } from 'element-plus'
// 用户搜索时选中的分类id
const parentColumnId = ref(null) // 父栏目ID

// 定义 subColumnId 用于存储选中的子栏目ID
const subColumnId = ref(null)

// 用户搜索时选中的发布状态
const state = ref('')

// 文章父级栏目数据模型
const parentColumns = ref([])

// 子栏目数据模型
const subColumns = ref([])

// 子栏目数据模型
const childColumns = ref([])


// 文章列表数据模型
const articles = ref([])

// 分页条数据模型
const pageNum = ref(1) // 当前页
const total = ref(20) // 总条数
const pageSize = ref(5) // 每页条数

// 添加分类表单校验
const rules = {
    title: [
        { required: true, message: '文章标题不能少', trigger: 'blur' },
    ]
}
// 控制抽屉是否显示
const visibleDrawer = ref(false)

// 添加表单数据模型
const articleModel = ref({
    title: '',
    parentColumnId: null, // 父栏目ID
    subColumnId: null, // 子栏目ID
    coverImageUrl: '', // 封面图片URL
    videoUrl: '', // 视频URL
    content: '', // 文章详情
    state: '' // 发布状态
})

const onSizeChange = (size) => {
    pageSize.value = size;
    getArticleListService(); // 确保在改变每页条数后重新获取数据
}

const onCurrentChange = (num) => {
    pageNum.value = num;
    getArticleListService(); // 确保在改变当前页码后重新获取数据
}

// 父栏目查询
const getpColumnListService = async () => {
    try {
        const resultC = await pColumnListService();
        parentColumns.value = resultC.data;
        // 移除默认选中的父栏目代码
    } catch (error) {
        console.error('获取父栏目列表失败', error);
    }
}


// 子栏目查询
const getcColumnListService = async () => {
    try {
        const resultC = await AllChildrencolumnsService();
        childColumns.value = resultC.data;
        // 移除默认选中的父栏目代码
    } catch (error) {
        console.error('获取所有子栏目列表失败', error);
    }
}
const onParentColumnChange = async () => {
    const parentId = parentColumnId.value;
    console.log('Parent column changed to:', parentId); // Debug log
    if (!parentId) return;

    // 清空子栏目选择
    subColumnId.value = null;

    // 获取子栏目列表
    await getSubColumns(parentId);
}

// 当父栏目选择变化时，重新获取子栏目列表
const onParentColumnChange2 = async (parentId) => {
    articleModel.value.subColumnId = null; // 清空子栏目选择
    subColumns.value = []; // 清空子栏目列表
    if (parentId) {
        await getSubColumns(parentId);
    }
};

const getSubColumns = async (parentId) => {
    console.log('Fetching sub-columns for parent ID:', parentId); // Debug log
    try {
        const resultS = await columnsService(Number(parentId));
        subColumns.value = resultS.data || [];
        console.log('Fetched sub-columns:', subColumns.value); // Debug log
    } catch (error) {
        console.error('获取子栏目列表失败', error);
    }
}

// 文章查询
const getArticleListService = async () => {
    try {
        const params = {
            parentColumnId: parentColumnId.value,
            subColumnId: subColumnId.value,
            state: state.value ? state.value : null,
            pageNum: pageNum.value,
            pageSize: pageSize.value
        };
        const result = await articleListService(params);
        articles.value = result.data.items || [];

        // 处理数据，给数据模型扩展 parentColumnName 和 subColumnName 属性
        articles.value.forEach(article => {
            // 查找父栏目名称
            const parentColumn = parentColumns.value.find(column => column.columnId === article.parentColumnId);
            article.parentColumnName = parentColumn ? parentColumn.name : '';

            // 查找子栏目名称
            const subColumn = childColumns.value.find(column => column.columnId === article.subColumnId);
            article.subColumnName = subColumn ? subColumn.name : '';
        });

        total.value = result.data.total || 0;
        console.log('Articles:', articles.value);

    } catch (error) {
        ElMessage.error('获取文章列表失败')
    }
}



const loadData = async () => {
    await getpColumnListService();
    await getcColumnListService();
    await getArticleListService(); // 确保在获取父栏目之后再获取文章列表
}

const searchArticles = async () => {
    await getArticleListService();
}

const resetFilters = () => {
    parentColumnId.value = null;
    subColumnId.value = null;
    state.value = '';
    pageNum.value = 1;
    pageSize.value = 3;
    searchArticles();
}

//导入token
import { useTokenStore } from '@/stores/token.js';
const tokenStore = useTokenStore();

//上传图片成功的回调函数
const uploadSuccess = (result) => {
    articleModel.value.coverImageUrl = result.data;
    ElMessage.success('图片上传成功');
    console.log(result.data);
}

//修改图片成功的回调函数
const uploadSuccess2 = (result) => {
    articleDetail.value.coverImageUrl = result.data;
    ElMessage.success('图片成功');
    console.log(result.data);
}
const addArticle = async (clickState) => {
    //将发布状态赋值给数据模型
    articleModel.value.state = clickState;
    //调用接口
    try {
        const result = await articleAddService(articleModel.value); // 等待异步函数完成
        console.log(result); // 现在可以打印出实际的结果
        ElMessage.success('文章添加成功');
    } catch (error) {
        console.error('添加文章失败:', error);
        ElMessage.error('文章添加失败');
    }
    resetArticleModel();
    //让抽屉消失
    visibleDrawer.value = false;

    //刷新当前列表
    getArticleListService();
}

// 处理视频上传成功的回调
const handleVideoSuccess = (result) => {
    articleModel.value.videoUrl = result.data; // 后端返回视频URL
    ElMessage.success('视频上传成功');
    console.log(result.data);
};
// 处理视频修改成功的回调
const handleVideoSuccess2 = (result) => {
    articleDetail.value.videoUrl = result.data; // 后端返回视频URL
    ElMessage.success('视频修改成功');
    console.log(result.data);
};

// 视频上传之前的钩子，用于校验
const beforeVideoUpload = (file) => {
    const isVideo = file.type.startsWith('video/');
    if (!isVideo) {
        ElMessage.error('只能上传视频文件!');
        return false;
    }
    const isLt500M = file.size / 1024 / 1024 < 500;
    if (!isLt500M) {
        ElMessage.error('上传视频大小不能超过 500MB!');
        return false;
    }
    return true;
};

// 定义响应式数据
const dialogVisible = ref(false);
const largeImageUrl = ref('');
const largeTitle = ref('');
const laegeDescription = ref('');
// 预览图片方法定义
const openImage = (url) => {
    largeImageUrl.value = url;
    dialogVisible.value = true;
};


// 文章详情数据模型
const articleDetail = ref({});

// 控制编辑抽屉是否显示
const visibleEditDrawer = ref(false);

// 当前正在编辑的文章ID
const currentEditArticleId = ref(null);

// 获取文章详情
const getArticleDetail = async (articleId) => {
    try {
        const result = await articleDetailService(articleId);
        articleDetail.value = result.data;
        // 设置子栏目
        onParentColumnChange2(articleDetail.value.parentColumnId);
        // 打开编辑抽屉
        visibleEditDrawer.value = true;
    } catch (error) {
        ElMessage.error('获取文章详情失败');
    }
};

// 更新文章方法
const updateArticle = async (clickState) => {
    try {
        // 如果 clickState 存在且不是事件对象，则更新 state
        if (clickState && typeof clickState === 'string') {
            articleDetail.value.state = clickState;
        }
        await articleUpdateService(articleDetail.value);
        ElMessage.success('文章更新成功');
        visibleEditDrawer.value = false;
        getArticleListService();
    } catch (error) {
        ElMessage.error('更新文章失败');
    }
};
// 处理编辑按钮点击事件
const handleEdit = (articleId) => {
    currentEditArticleId.value = articleId;
    getArticleDetail(articleId);
};

// 文章数据模型的重置方法
const resetArticleModel = () => {
    articleModel.value = {
        title: '',
        parentColumnId: null,
        subColumnId: null,
        coverImageUrl: '',
        videoUrl: '',
        content: '',
        state: ''
    };
}

// 删除文章的方法
const deleteArticle = async (row) => {

    await ElMessageBox.confirm('确定要删除这篇文章吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    });

    const response = await deleteArticleService(row.articleId);
    if (response.code === 200) {
        ElMessage.success('删除成功');
        // 删除成功后，重新获取文章列表
        getArticleListService();
    } else {
        ElMessage.error('删除失败');
    }
};

// 添加富文本编辑器配置
const editorOptions = {
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],    // 加粗、斜体、下划线、删除线
      ['blockquote', 'code-block'],                 // 引用、代码块
      [{ 'header': 1 }, { 'header': 2 }],          // 标题1、标题2
      [{ 'list': 'ordered'}, { 'list': 'bullet' }], // 有序列表、无序列表
      [{ 'script': 'sub'}, { 'script': 'super' }],  // 下标、上标
      [{ 'indent': '-1'}, { 'indent': '+1' }],      // 减少缩进、增加缩进
      [{ 'direction': 'rtl' }],                     // 文字方向
      [{ 'size': ['small', false, 'large', 'huge'] }], // 字体大小
      [{ 'header': [1, 2, 3, 4, 5, 6, false] }],    // 标题
      [{ 'color': [] }, { 'background': [] }],      // 字体颜色、背景颜色
      [{ 'font': [] }],                             // 字体
      [{ 'align': [] }],                           // 对齐方式
      ['clean'],                                    // 清除格式
      ['link', 'image', 'video']                    // 链接、图片、视频
    ]
  },
  placeholder: '请输入内容...'
}

onMounted(() => {
    loadData();
});
</script>

<style lang="scss" scoped>
.cell-ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
        /* 表格表头样式 */
        :deep(.el-table__header th) {
    background-color: #ededed; 
    font-size: 14px; 
    color: #717171;

    // padding: 15px;
  
  }

    /* 斑马条纹效果 */
    ::v-deep(.el-table__body tr:nth-child(odd)) {
        background-color: #f9fafc;
    }

    ::v-deep(.el-table__body tr:nth-child(even)) {
        background-color: #ffffff;
    }

    /* 状态标签样式 */
    ::v-deep(.el-tag--success) {
        color: #fff;
        background-color: #67c23a;
        border-color: #67c23a;
    }

    ::v-deep(.el-tag--info) {
        color: #fff;
        background-color: #909399;
        border-color: #909399;
    }

    // 修改下拉框的宽度
    .el-select {
        width: 200px;
    }
}

/* 抽屉样式 */
.avatar-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}

.editor {
    width: 100%;
    
    :deep(.ql-editor) {
        min-height: 200px;
        max-height: 400px;
        overflow-y: auto;
        font-size: 14px;
        line-height: 1.6;
    }
    
    :deep(.ql-toolbar) {
        border-radius: 4px 4px 0 0;
        background-color: #f5f7fa;
        border-color: #dcdfe6;
    }
    
    :deep(.ql-container) {
        border-radius: 0 0 4px 4px;
        border-color: #dcdfe6;
        max-height: 442px; /* 工具栏高度 + 编辑器最大高度 */
        overflow: hidden;
    }
    
    :deep(.ql-toolbar button:hover),
    :deep(.ql-toolbar button:focus) {
        color: var(--el-color-primary);
    }
    
    :deep(.ql-toolbar button.ql-active) {
        color: var(--el-color-primary);
    }
    
    /* 自定义滚动条样式 */
    :deep(.ql-editor::-webkit-scrollbar) {
        width: 6px;
    }
    
    :deep(.ql-editor::-webkit-scrollbar-track) {
        background: #f1f1f1;
        border-radius: 3px;
    }
    
    :deep(.ql-editor::-webkit-scrollbar-thumb) {
        background: #c1c1c1;
        border-radius: 3px;
    }
    
    :deep(.ql-editor::-webkit-scrollbar-thumb:hover) {
        background: #a8a8a8;
    }
}
</style>